import React, { useState, useMemo, useEffect, useRef, useCallback } from "react";
import { Form, Button, Popconfirm, Tooltip, message, Row, Col } from "antd";
import { find } from "lodash";
import { CommonModal } from "@/views/components/CommonModal";
import CommonTable from "@/components/CommonTable";
import { cloneDeep, isEmpty } from "lodash";
import { Input, Select, BatchSuffixInput } from "@/views/components/PrefixPlaceholder";
import BatchSelectModal from "./BatchSelectModal";
import AreaCodeSelect from "@/pages/PurchaseModule/propose/components/Actions/AreaCodeSelect";
import CommonStoreSearchInput from "@/views/components/CommonStoreSearchInput/index";

import { getFindSupplierNumPage, fmcgpurchasesUpdateFmcgPurchaseSupplier } from "../service";
const { Option } = Select;

//渲染交接员工
const renderSubUser = item => {
	if (item.name) {
		if (item.account) {
			return item.name + "(" + item.account + ")";
		} else {
			return item.name;
		}
	} else {
		return "";
	}
};

export default ({ userData, handleOk, handleCancel, fetchList, areaOption }) => {
	const [list, setList] = useState([]);
	const [source, setSource] = useState([]);

	const [visible, setVisible] = useState(false);

	const [checked, setChecked] = useState(false);

	const [fixedRows, setFixedRows] = useState([]);

	const [form] = Form.useForm();
	const rowKey = "supplierId";

	const data = useMemo(() => {
		return source;
	}, [source]);
	const handleUserList = async value => {
		const { data, success } = await getFindSupplierNumPage({
			storeName: value ? value.storeName : "",
			shopAreaName: value ? value.shopAreaName : ""
		});
		if (success) {
			let list = [...new Set([...data, ...fixedRows])];
			const uniqueBySupplierId = list.reduce((accumulator, currentItem) => {
				const index = accumulator.findIndex(item => item.supplierId === currentItem.supplierId);
				if (index === -1) {
					accumulator.push(currentItem);
				}
				return accumulator;
			}, []);
			setSource(uniqueBySupplierId);
			setList(uniqueBySupplierId);
		}
	};

	const handleSelect = (e, r, supplierId) => {
		const obj = find(source, ["supplierId", supplierId]);
		if (obj) {
			obj.pickerId = e;
		}
		fixedRows?.map(x => {
			if (x.supplierId == r.supplierId) {
				x.pickerId = e;
			}
		});
		source?.map(x => {
			if (x.supplierId == r.supplierId) {
				x.pickerId = e;
			}
		});
		console.log(source, "sourcesourcesource");
		setSource(JSON.parse(JSON.stringify(source)));
	};

	const columns = [
		{
			title: "供应商",
			dataIndex: "supplier",
			key: "supplier"
		},
		{
			title: "拿货任务数",
			dataIndex: "num",
			key: "num"
		},
		{
			title: "拿货员",
			dataIndex: "pickerId",
			key: "pickerId",
			width: 200,
			render: (text, r, { supplierId }) => {
				return (
					<Select
						style={{ width: "100%" }}
						showSearch
						origin
						placeholder="请选择或者输入检索"
						optionFilterProp="children"
						filterOption={(input, option) => (option?.label ?? "").toLowerCase().includes(input.toLowerCase())}
						onChange={e => handleSelect(e, r, supplierId)}
						value={text}
					>
						{userData.map(item => {
							const content = renderSubUser(item);
							return (
								<Option value={item.id} key={item.id} label={content}>
									<Tooltip title={content}>{content}</Tooltip>
								</Option>
							);
						})}
					</Select>
				);
			}
		},
		{
			title: "操作",
			dataIndex: "supplierId",
			key: "supplierId",
			render: (t, r, i) => (
				<span className="opera-span-common">
					{checkRowIncludes(r) ? (
						<Popconfirm title="确定删除该条数据?" onConfirm={() => onRowClickToDelete(r)}>
							<a href="#" disabled={r.isDefault == 0}>
								删除
							</a>
						</Popconfirm>
					) : (
						<a onClick={() => onRowClickToAdd(r)}>添加</a>
					)}
				</span>
			)
		}
	];

	const tableProps = {
		data,
		columns,
		rowKey: "supplierId",
		scroll: { y: 480 }
	};

	const batchSelectProps = {
		visible: visible == 1,
		userData,
		handleOk(pickerId) {
			list.map(item => {
				item.pickerId = pickerId;
			});
			setSource(JSON.parse(JSON.stringify(list)));
			setVisible(false);
		},
		handleCancel() {
			setVisible(false);
		}
	};
	// 判断
	const checkRowIncludes = useCallback(
		row => {
			return fixedRows.find(e => e[rowKey] === row[rowKey]);
		},
		[fixedRows]
	);
	// 添加
	const onRowClickToAdd = e => {
		setFixedRows(prev => [...prev, e]);
	};
	// 删除
	const onRowClickToDelete = item => {
		item.isChecked = false;
		setFixedRows(prev => {
			return prev.filter(x => x[rowKey] !== item[rowKey]);
		});
		message.success("删除操作成功");
	};
	// 固定添加的数据
	const refFixedRows = useRef([]);
	useEffect(() => {
		refFixedRows.current = cloneDeep(fixedRows);
	}, [fixedRows]);
	const handleBatch = () => {
		setVisible(1);
	};

	const onOk = () => {
		form.validateFields().then(async value => {
			console.log(fixedRows, "fixedRows");
			if (fixedRows.length == 0) {
				return message.error("请选择添加供应商");
			} else {
				console.log(source, "source");
				source?.forEach(i => {
					fixedRows.forEach(x => {
						if (x.supplierId == i.supplierId) {
							x.pickerId = i.pickerId;
						}
					});
				});
				let pickerIdArray = fixedRows.filter(obj => "pickerId" in obj).map(obj => obj.pickerId);
				console.log(fixedRows, "fixedRows");
				if (pickerIdArray.length != fixedRows.length) {
					return message.error("请选择拿货员");
				} else {
					const { success } = await fmcgpurchasesUpdateFmcgPurchaseSupplier(fixedRows);
					if (success) {
						fetchList();
						message.success("操作成功");
						handleCancel();
					}
				}
			}
		});
	};

	const handleSearch = () => {
		form.validateFields().then(async value => {
			const data = value?.shopAreaName?.map(x => x.label);
			value.shopAreaNam = data?.join(",");
			let param = {
				shopAreaName: data?.join(","),
				storeName: value?.storeName?.join(",")
			};
			handleUserList(param);
		});
	};

	const onReset = () => {
		form.resetFields();
		handleUserList();
	};

	return (
		<>
			<CommonModal
				visible={true}
				className="views-table-dialog"
				title={{ title: "供应商指派" }}
				onCancel={handleCancel}
				minHeight="150px"
				onOk={onOk}
				width="624px"
			>
				<div>
					<Form form={form} layout="inline" onFinish={handleSearch}>
						<Row style={{ width: "100%" }}>
							<Col span={8}>
								<Form.Item label="" name="storeName">
									<CommonStoreSearchInput
										type="storeName"
										// origin
										maxTagCount={1}
										mode="multiple"
										valueKey="storeName"
										placeholder="供应商名称"
									/>
								</Form.Item>
							</Col>
							<Col span={8} style={{ marginRight: 12 }}>
								<Form.Item label="" name="shopAreaName">
									{/* <BatchSuffixInput autoMultiLine allowClear clearable placeholder="多个供应商，以逗号隔开" /> */}

									<AreaCodeSelect
										origin="true"
										labelInValue={"labelInValue"}
										placeholder="区域编码"
										mode="multiple"
										options={areaOption.current}
										showArrow={false}
										maxTagCount={2}
										style={{ lineHeight: "22px", width: "100%" }}
									/>
								</Form.Item>
							</Col>
							<Col span={6}>
								<Form.Item>
									<Button type="primary" htmlType="submit" style={{ marginRight: "8px" }}>
										查询
									</Button>
									<Button onClick={onReset}>重置</Button>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</div>
				<Button style={{ marginBottom: 12 }} onClick={handleBatch}>
					批量指派
				</Button>
				{visible == 1 && <BatchSelectModal {...batchSelectProps} />}
				<CommonTable {...tableProps} />
			</CommonModal>
		</>
	);
};
